package com.buy.schedule;

import com.buy.dao.InstantBuyDao;
import com.common.domain.InstantBuyItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-24 15:01
 * @description
 * @copyright 2021
 */
@Component
public class ScanTime {
  @Autowired private StringRedisTemplate redisTemplate;

  @Autowired private InstantBuyDao instantBuyDao;

  /** 定时任务用于将符合条件的秒杀商品添加到redis */
  @Scheduled(fixedRate = 5000)
  public void addItemToRedis() {
    List<InstantBuyItem> items = instantBuyDao.selectItems(new Date());
    for (InstantBuyItem item : items) {
      String itemId = item.getItemId();
      Date startTime = item.getStartTime();
      Date endTime = item.getEndTime();
      Date nowTime = new Date();
      if (nowTime.compareTo(endTime) > 0) {
        //若扫描出的商品有过期的，就删掉
        redisTemplate.delete("INSTANT_" + itemId);
        continue;
      }
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      redisTemplate.opsForHash().put("INSTANT_" + itemId, "number", item.getNumber().toString());
      redisTemplate.opsForHash().put("INSTANT_" + itemId, "start_Time", df.format(startTime));
      redisTemplate.opsForHash().put("INSTANT_" + itemId, "end_Time", df.format(endTime));
    }
  }
}
